package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleStaticHtml;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 自媒体发布文章并保存奥App端的文章库中后，将文章内转换为Html并上传到minio
 */
@Slf4j
@Service
public class ApArticleStaticHtmlImpl implements ApArticleStaticHtml {
    @Autowired
    private Configuration configuration;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private ApArticleMapper apArticleMapper;

    @Override
    public void buildApArticleStaticHtml(ApArticle apArticle, String content) {
        try {
            //1准备数据模型
            Map<String,Object> dataModel = new HashMap<>();
            dataModel.put("content", JSON.parseArray(content));

            //2.加载模板
            Template template = configuration.getTemplate("article.ftl");

            //3.填充数据生成静态页面
            //3.1创建字符输出流存储到内存缓存中
            StringWriter writer = new StringWriter();
            //3.2调用process生成页面
            template.process(dataModel,writer);

            //4上传到minio（调用heima-file-starter中的服务进行上传）
            //4.1将内存缓存中数据通转为输出流
            ByteArrayInputStream is = new ByteArrayInputStream(writer.toString().getBytes());
            //4.2上传,获取路径
            String url = fileStorageService.uploadHtmlFile("", apArticle.getId() + ".html", is);

            //5.修改ap_article表中的static_url字段
            //5.1查询文章详情
            ApArticle article = apArticleMapper.selectById(apArticle.getId());
            //5.2修改static_url字段，并保存到数据库
            article.setStaticUrl(url);
            apArticleMapper.updateById(article);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("文章生成静态页面失败，文章id:{},失败原因:{}",apArticle.getId(),e.getMessage());
        }
    }
}
